<template>
  <div class="chat-container">
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message-wrapper', message.isUser ? 'user-wrapper' : 'ai-wrapper']">
        <div v-if="!message.isUser" class="avatar">
          <img :src="aiAvatar" alt="AI" />
        </div>
        <div :class="['message', message.isUser ? 'user-message' : 'ai-message']">
          <div class="message-content">
            {{ message.content }}
          </div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="请输入您的问题..."
        @keyup.enter="sendMessage"
        :disabled="isLoading"
      >
        <template #append>
          <el-button @click="sendMessage" :loading="isLoading">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'

const props = defineProps({
  apiEndpoint: {
    type: String,
    required: true
  },
  chatId: {
    type: String,
    required: true
  },
  aiAvatar: {
    type: String,
    default: '/ai-avatar.png'
  }
})

const messages = ref([])
const inputMessage = ref('')
const messagesContainer = ref(null)
const isLoading = ref(false)
let eventSource = null

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

watch(messages, () => {
  scrollToBottom()
})

const sendMessage = () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value
  messages.value.push({
    content: userMessage,
    isUser: true
  })
  inputMessage.value = ''
  isLoading.value = true

  // 关闭之前的连接
  if (eventSource) {
    eventSource.close()
  }

  // 创建新的 EventSource 连接
  const url = `${props.apiEndpoint}?message=${encodeURIComponent(userMessage)}&chatId=${encodeURIComponent(props.chatId)}`
  eventSource = new EventSource(url)

  // 添加 AI 消息占位
  messages.value.push({
    content: '',
    isUser: false
  })

  // 处理消息
  eventSource.onmessage = (event) => {
    const lastMessage = messages.value[messages.value.length - 1]
    if (!lastMessage.isUser) {
      lastMessage.content += event.data
    }
  }

  // 处理错误
  eventSource.onerror = (error) => {
    console.error('SSE Error:', error)
    eventSource.close()
    const lastMessage = messages.value[messages.value.length - 1]
    if (!lastMessage.isUser && !lastMessage.content) {
      lastMessage.content = '抱歉，发生了错误，请稍后重试。'
    }
    isLoading.value = false
  }

  // 处理完成
  eventSource.onclose = () => {
    isLoading.value = false
  }
}

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg-color);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem 0.5rem 1.5rem 0.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  max-width: 85%;
}

.user-wrapper {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-wrapper {
  align-self: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  background: #222;
  border: 1.5px solid var(--primary-color);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message {
  padding: 0.85rem 1.2rem;
  border-radius: 1rem;
  font-size: 1rem;
  line-height: 1.7;
  box-shadow: 0 2px 12px 0 rgba(0,255,157,0.08);
}

.user-message {
  background: var(--primary-color);
  color: #fff;
  border-top-right-radius: 0.25rem;
  font-weight: 600;
  box-shadow: 0 0 8px 0 #00ff9d55;
}

.ai-message {
  background: #23272e;
  color: #f4faff;
  border-top-left-radius: 0.25rem;
  font-weight: 500;
  box-shadow: 0 0 12px 0 #00b8ff33;
  border: 1px solid var(--border-color);
}

.message-content {
  word-wrap: break-word;
  white-space: pre-wrap;
  text-align: left;
  color: inherit;
}

.chat-input {
  padding: 1rem;
  background: #181c20;
  border-top: 1.5px solid var(--border-color);
}

:deep(.el-input__wrapper) {
  background: #23272e;
  border: 1.5px solid var(--border-color);
  box-shadow: none;
}
:deep(.el-input__inner) {
  color: #fff;
  background: transparent;
}
:deep(.el-button) {
  background: var(--primary-color);
  color: #fff;
  border: none;
  font-weight: bold;
}
:deep(.el-button):hover {
  filter: brightness(1.1);
}

@media (max-width: 768px) {
  .message-wrapper {
    max-width: 98%;
  }
  .message {
    padding: 0.6rem 0.8rem;
    font-size: 0.95rem;
  }
  .avatar {
    width: 32px;
    height: 32px;
  }
}
</style> 